<template>
  <div class="m-4">
    <BasicForm :labelWidth="100" @register="registerForm" :actionColOptions="{ span: 8 }" :baseColProps="{ span: 3 }" @submit="handleSubmit" />
  </div>
  <div style="margin-top: 16px">
    <!-- tabs 页面 -->
    <div class="tabs">
      <a-tabs v-model:activeKey="tabsKey" @change="handleTabsChange">
        <a-tab-pane v-for="(item, index) in workList" :key="item.xsCode" :disabled="item.isDefault" :tab="item.xsName" />
        <!-- <a-tab-pane key="role" tab="工作角色系数" :disabled="workConfigShow1"></a-tab-pane> -->
      </a-tabs>
    </div>
    <div>
      <!--引用表格-->
      <BasicTable @register="registerTable">
        <!--插槽:table标题-->
        <template #tableTitle>
          <a-button type="primary" preIcon="ant-design:plus-outlined" @click="handleAdd"> 新增</a-button>
          <a-button @click="handleSaveList">保存</a-button>
          <a-button preIcon="ant-design:save-outlined" @click="editCancel" v-if="startEdit">取消</a-button>
          <a-button type="primary" preIcon="ant-design:export-outlined" @click="onExportXls"> 导出</a-button>
          <j-upload-button type="primary" preIcon="ant-design:import-outlined" @click="onImportXls">导入</j-upload-button>
        </template>
        <template #bodyCell="{ column, record }">
          <!-- 下拉框插槽(单位层级) -->
          <template v-if="column.editRow && column.dataIndex === 'unitLevel'">
            <a-select v-model:value="record[column['dataIndex']]" style="width: 100%" :dropdown-style="{ maxHeight: '400px', overflow: 'auto' }" placeholder="请选择" :fieldNames="{ label: 'orgTypeName', value: 'orgTypeCode' }" :options="orgData" allow-clear />
          </template>
          <template v-if="column.editRow && column.editComponent === 'Switch'">
            <a-switch checkedChildren="是" unCheckedChildren="否" :checkedValue="'true'" :unCheckedValue="'false'" size="small" v-model:checked="record[column['dataIndex']]" />
          </template>
          <template v-if="column.editRow && column.editComponent === 'Input'">
            <a-input v-model:value="record[column['dataIndex']]" />
          </template>
          <template v-if="column.editRow && column.editComponent === 'InputNumber'">
            <a-input-number v-model:value="record[column['dataIndex']]" :controls="false" />
          </template>
        </template>
        <!--操作栏-->
        <template #action="{ record }">
          <TableAction :actions="getTableAction(record)" />
        </template>
      </BasicTable>
      <!-- 表单区域 -->
      <HubTeamXsItemModal @register="registerModal" @success="handleSuccess" />
    </div>
  </div>
</template>

<script lang="ts" name="emp-hubTeamXsItem" setup>
import { ref, reactive, onMounted } from 'vue';
import { BasicTable, TableAction } from '/@/components/Table';
import { BasicForm, FormSchema, useForm } from '/@/components/Form';
import { useModal } from '/@/components/Modal';
import { useListPage } from '/@/hooks/system/useListPage'
import HubTeamXsItemModal from './components/HubTeamXsItemModal.vue'
import { columns, searchFormSchema } from './HubTeamXsItem.data';
import { list, deleteOne, getImportUrl, getExportUrl, getWorkList, updateBatch } from './HubTeamXsItem.api';
import { useMessage } from '/@/hooks/web/useMessage'; // 轻提醒
const { createMessage: $message } = useMessage(); // 解构
const queryParam = reactive<any>({});
  import { useUserStore } from '/@/store/modules/user';
const userStore = useUserStore();

//注册model
const [registerModal, { openModal }] = useModal();
// 控制操作列的的显示与隐藏
const showActionColumn = ref(true);
//注册table数据
const { tableContext, onExportXls, onImportXls } = useListPage({
  tableProps: {
    title: '工作系数参数配置表',
    api: list,
    columns,
    canResize: false,
    showIndexColumn: true,
    showActionColumn: showActionColumn,
    actionColumn: {
      width: 120,
      fixed: 'right'
    },
    immediate: false,
    beforeFetch: async (params) => {
      return Object.assign(params, queryParam);
    },
  },
  exportConfig: {
    name: "工作系数参数配置",
    url: getExportUrl,
    params: queryParam,
  },
  importConfig: {
    url: getImportUrl,
    success: handleSuccess
  },
})


//自定义
let state = ref('edit');
let addNum = ref(0);
const startEdit = ref<boolean>(false);
const workList = ref([{
  xsCode: '',
  xsName: '',
}]);
// tab页选中数据
const tabsKey = ref('');

// 注册表单数据
const [registerForm, { setProps, updateSchema, setFieldsValue, getFieldsValue }] = useForm({
  labelWidth: 120,
  schemas: searchFormSchema,
});
const [registerTable, { reload,getDataSource, setColumns, setTableData, getColumns }, { selectedRowKeys }] = tableContext

// 默认执行一次
onMounted(async () => {
  updateSchema([
    {
      field: 'orgCode',
      componentProps: {
        onChange: (e) => {
          // setTableData([]);
          $message.info("班组切换了111，"+e)
          initTeamWorkListTabs(e);
        },
        // atfer request callback
        onOptionsChange: (options) => {
          console.log('get options', options.length, options);
        },
      },
    },
  ]);
  initTeamWorkListTabs(userStore.getOrgCode);
});

/**
 * 初始化班组工作系数tabs
 */
async function initTeamWorkListTabs(orgCode?) {
  let params = {
    orgCode: orgCode? orgCode: getFieldsValue().orgCode,
  };
  await getWorkList(params).then((res) => {
    if (!res || res.length == 0) {
      return;
    }
    workList.value = res;
    tabsKey.value = res[0].xsCode;
    handleSuccess();
  });
}

/**
 * 新增事件
 */
function handleAdd() {
  startEdit.value = true;
  state.value = 'add';
  // showActionColumn.value = false;
  addNum.value++;
  const data = getDataSource();
  data.unshift({});
}

// 批量保存
async function handleSaveList() {
  state.value = 'edit';
  // startEdit.value = false;
  let params = getFormParams();
  let orgCode = params.orgCode;
  if (state.value === 'edit') {
    const data = getDataSource();
    let flagSave = false;
    let saveMsg = '';
    data.forEach((item) => {
      if (!item.workName) {
        flagSave = true;
      }
      workList.value.forEach((work) => {
        if (work.xsCode == tabsKey.value) {
          item.xsName = work.xsName;
          saveMsg = work.xsName;
        }
      });
      item.xsCode = tabsKey.value;
      // item.xsName =
      item.orgCode = orgCode;
      delete item.editId;
    });
    if (flagSave) {
      $message.error(`${saveMsg}名称不能为空！`);
      return;
    }
    let list = {
      datas: data,
      orgCode: orgCode,
    };

    await updateBatch(list).then(async (res) => {
      if (res) {
        handleSuccess();
        state.value = 'edit';
        startEdit.value = false;
        showActionColumn.value = true;
      }
    });
  }
}
//取消事件
const editCancel = () => {
  const data = getDataSource();
  let newData = data.filter((item) => item.id);
  setTableData(newData);
  $message.info('已取消');
  state.value = '';
  startEdit.value = false;
};
/**
 * 编辑事件
 */
function handleEdit(record: Recordable) {
  openModal(true, {
    record,
    isUpdate: true,
    showFooter: true,
  });
}
/**
 * 删除事件
 */
async function handleDelete(record) {
  await deleteOne({ id: record.id }, handleSuccess);
}
/**
 * 成功回调
 */
function handleSuccess() {
  //清空表格数据
  selectedRowKeys.value = [];
  let params = getFormParams();
  // console.log('表单数据', params);
  reload({ searchInfo: params });
}
/**
 * 表格操作栏
 */
function getTableAction(record) {
  return [
    {
      label: '编辑',
      icon: 'clarity:note-edit-line',
      onClick: handleEdit.bind(null, record)
    },
    {
      label: '删除',
      icon: 'ant-design:delete-outlined',
      color: 'error',
      popConfirm: {
        title: '是否确认删除',
        placement: 'left',
        confirm: handleDelete.bind(null, record),
      }
    }
  ]
}

/**
 * 获取表单参数
 */
function getFormParams() {
  let formData = getFieldsValue();
  let params = Object.assign({ xsCode: tabsKey.value }, formData);
  return params;
}

// 提交事件
function handleSubmit() {
  handleSuccess();
}

// tabs切换事件
function handleTabsChange() {
  //改变表头数据
  let tabColumns = getColumns();
  workList.value.forEach((list) => {
    if (list.xsCode == tabsKey.value) {
      tabColumns[2].title = `${list.xsName}名称`;
      tabColumns[3].title = `${list.xsName}系数`;
    }
  });
  setColumns(tabColumns);
  handleSuccess();
}
</script>

<style lang="less" scoped>
:deep(.ant-picker),
:deep(.ant-input-number) {
  width: 100%;
}

.tabs {
  width: 100%;
  background-color: #fff;
  padding-left: 7px;
  padding-right: 7px;
}

.m-4 {
  background-color: #fff;
  padding-top: 20px;
  margin: 0px;
}

.formBox {
  margin: 10px;
  /* width: 100%; */
  height: 60px;
  background-color: #fff;
}
</style>